import 'package:series_play/bean/user_info_result_data.dart';
import 'package:series_play/comm/base/app_controller.dart';
import 'package:series_play/comm/sp_constant.dart';
import 'package:series_play/net/api/account_api.dart';
import 'package:series_play/utils/sp.dart';
import 'package:get/get.dart';

class UserManager {
  static String? token;

  /// 检查是否已登录
  ///
  /// token 不为空就算已登录
  static Future<void> checkLogin() async {
    // 本地token
    final token = await Sp.getStr(SpConstant.userToken, def: '');
    // 当前用户身份
    final isGuest = await UserManager.isGuest();
    final appController = Get.find<AppController>();
    // token 不为空获取用户信息
    if (token.isNotEmpty) {
      // 保存用户信息到全局
      appController.userInfo.value = await refreshUserInfo();
    }
    // 保存用户身份到全局
    appController.loginIdentity.value = isGuest
        ? LoginIdentity.guest
        : LoginIdentity.formalUser;
  }

  /// 游客登录
  static Future<bool> guestLogin() async {
    final result = await AccountApi.instance.guestLogin();
    if (result.isSuccess) {
      UserManager.saveToken(LoginIdentity.guest, result.data?.token ?? '');
    }
    return result.isSuccess;
  }

  /// 保存token 同时确定登录用户身份
  static Future<void> saveToken(LoginIdentity identity, String token) async {
    UserManager.token = token;
    await Sp.putInt(SpConstant.loggedInIdentity, identity.index);
    await Sp.putStr(SpConstant.userToken, token);
    checkLogin();
  }

  /// 获取本地token
  static Future<String> getToken() async {
    return token ??= await Sp.getStr(SpConstant.userToken);
  }

  /// 是否是游客
  static Future<bool> isGuest() async {
    final identity = await Sp.getInt(
      SpConstant.loggedInIdentity,
      def: LoginIdentity.guest.index,
    );
    return identity == LoginIdentity.guest.index;
  }

  /// 刷新当前用户信息
  ///
  /// 这里要更新到缓存以及全局状态中
  static Future<UserInfoData?> refreshUserInfo() async {
    final result = await AccountApi.instance.selfInfo();
    if (result.isSuccess) {
      return result.data?.userInfo;
    }
    return null;
  }

  static Future<void> logout() async {
    UserManager.token = null;
    await Sp.remove(SpConstant.userToken);
    await Sp.remove(SpConstant.loggedInIdentity);
    await guestLogin();
    checkLogin();
  }
}

enum LoginIdentity {
  /// 登录者身份：游客
  guest,

  /// 登录者身份：正式用户
  formalUser,
}
